var entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    Q = require('q'),
    mongoose = require('mongoose');
//更新流水信息
exports.updateBizRecordByValue = function(bizRecordId, value, completeFun) {
    var entity = entityCollection.getEntity("BizRecord");
    entity.updateByValue({ _id: bizRecordId}, value, function(err, result) {
        completeFun(err, result);
    });
};

//查找条码的所有流水(按时间降序)
exports.findAllByBarcodeMasterAndWork = function(barcodMasterId, workId, completeFun) {
    var entity = entityCollection.getEntity("BizRecord");
    entity.find({
        BarcodeMaster: barcodMasterId,
        Work: workId
    }, {CollectDateTime: -1}, null, function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询条码流水错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};
//查找条码流水
exports.findByBarcodeMasterAndWork = function(barcodMasterId, workId, completeFun) {
    var entity = entityCollection.getEntity("BizRecord");
    entity.findOne({
        BarcodeMaster: barcodMasterId,
        Work: workId
    }, [{ path: 'Users' }, { path: 'QCUser' }], function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '语法错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

//创建条码流水
exports.insert = function(bizRecordData, completeFun) {
    var bizRecordEntity = entityCollection.getEntity("BizRecord");
    bizRecordEntity.insert(bizRecordData, function(err, newBizRecord) {
        completeFun(err, newBizRecord);
    });
};

//删除条码流水
exports.deleteById = function(bizRecordId, completeFun) {
    var bizRecordEntity = entityCollection.getEntity("BizRecord");
    bizRecordEntity.deleteById(bizRecordId, function(err, result) {
        completeFun(err, result);
    });
};

// 查找单品所有流水，并按部门分组
exports.findByBarcodeMaster = function(barcodeMasterIds, completeFun) {
    var entity = entityCollection.getEntity("BizRecord");
    entity.find({ BarcodeMaster: { $in: barcodeMasterIds} }, { CollectDateTime: 1 }, [{
        path: 'Users',
        select: 'Code Name'
    }, {
        path: 'WorkLocation',
        select: 'Code Name Department',
        populate: {
            path: 'Department',
            select: 'Code Name',
            model: 'Department'
        }
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '语法错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

// 仅供压力测试使用：更新一条条码流水记录
exports.updateOneST = function(barcodMasterId, completeFun) {
    var entity = entityCollection.getEntity("BizRecord");
    entity.findOne({ BarcodeMaster: barcodMasterId }, null, function(err, record) {
        if (err || !record) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '语法错误，请检查查询参数！';
            completeFun(newErr);
            return;
        }
        record.BusinessStatus = 1;
        entity.update(record, function(err, modifyRecord) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询错误';
                newErr.message = '语法错误，请检查查询参数！';
                completeFun(newErr);
                return;
            }
            completeFun(null, modifyRecord);
        });
    });
};

// 根据工位查询最近一条流水档记录
exports.findNearestRecord = function(workLocationId) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("BizRecord");
    entity.Entity
        .find({ WorkLocation: workLocationId })
        .sort({ CollectDateTime: -1 })
        .limit(1)
        .exec(function(err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询错误';
                newErr.message = '语法错误，请检查查询参数！';
                deferred.reject(newErr);
                return;
            }
            deferred.resolve(records);
        });

    return deferred.promise;
}

//首页-质量预警
exports.qualityWaring = function(completeFun) {
    mapReduceByDate().then(function(results) {
        completeFun(null, results);
    }, function(err) {
        completeFun(err);
    });
};

//按时间分组查找流水档
function mapReduceByDate() {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("BizRecord");
    var barcodeMap = function() {
        var date = this.CollectDateTime;
        var year = date.getFullYear();
        var month = date.getMonth();
        var day = date.getDate();
        var key = year + "-" + month + "-" + day;
        emit(key, { bizRecords: [this] });
    };
    var barcodeReduce = function(key, values) {
        var res = {
            bizRecords: []
        };
        values.forEach(function(val) {
            val.bizRecords.forEach(function(obj) {
                res.bizRecords.push(obj);
            });
        });
        return res;
    };

    var barcodeQuery = {
        QCStatus: 1
    };

    var option = {
        map: barcodeMap,
        reduce: barcodeReduce,
        sort: { QCDateTime: 1 },
        query: barcodeQuery
    };
    entity.mapReduce(option, function(err, results) {
        if (err) {
            deferred.reject(err);
        }
        deferred.resolve(results);
    });

    return deferred.promise;
}
